import { getinviteKey, getToken } from "../../utils/storage";
import { loadingInfo } from "../../api/invitetest";
import {
  getInviteList,
  getTokenById,
  getUserInfo,
  getPosterQRcode,
} from "../../api/user";
const app = getApp()
// import { threadId } from 'worker_threads';
import { SHOW_COUNT, getSharePng } from "../../config";
// pages/invite/invite.js

const showCount = 30 || SHOW_COUNT;
let currentPage = 1;
let totalPage = 1;
let user_name = "";

let loading = false;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showpopup: true,
    page: 1,
    userlist: [],
    inviteInfo: {},
    // animationData: {},

    my_invite_key: getinviteKey(),
    my_invite_list: [],

    tip_status: false,
    // 四项收益
    kbx_share_rate: 0.1,
    shar_rate: 0.12,
    earning_giftshare: 0,
    earning_gbox: 0, // 开宝箱收益
    scene: null,
    totalResult: 0,
    bgImage:
      "https://ustatic.hudongmiao.com/joymew-assistant/invite/invite_bill.png",
    imagePath: "",
    QRcodeUrl: "",
    incomePercentage: "",
    userphoneNumber: "",
    token: getToken(),
    back: false
  },

  //复制电话
  copePhonenum: function (e) {
    wx.setClipboardData({
      data: e.target.dataset.phone,
      success() {
        wx.showToast({
          title: "复制微信号成功，快添加好友教他使用嗨喵吧.",
          duration: 3000,
          icon: "none",
        });
      },
    });

  },
  //拨打电话
  freeTell: function (e) {

    wx.makePhoneCall({
      phoneNumber: e.target.dataset.phone,
    });
  },
  /**
   * 获取用户信息
   */
  initUserInfo() { },
  showTips() {
    const tip_status = this.data.tip_status;
    // 
    this.setData({
      tip_status: !tip_status,
    });
  },
  handleInviteList(res) {
    if (res.data) {
      if (res.data.kbx_share_rate || res.data.kbx_share_rate === 0) {
        this.setData({
          kbx_share_rate: res.data.kbx_share_rate,
        });
      }

      if (res.data.shar_rate || res.data.shar_rate === 0) {
        this.setData({
          shar_rate: res.data.shar_rate,
        });
      }

      if (res.data.totalincome) {
        if (res.data.totalincome.kbx_share_income) {
          res.data.totalincome.earning_gbox =
            res.data.totalincome.kbx_share_income;
        }
        if (res.data.totalincome.gift_share_income) {
          res.data.totalincome.earning_giftshare =
            res.data.totalincome.gift_share_income;
        }

        if (
          res.data.totalincome.earning_giftshare ||
          res.data.totalincome.earning_giftshare === 0
        ) {
          this.setData({
            earning_giftshare: res.data.totalincome.earning_giftshare,
          });
        }

        if (
          res.data.totalincome.earning_gbox ||
          res.data.totalincome.earning_gbox === 0
        ) {
          this.setData({
            earning_gbox: res.data.totalincome.earning_gbox,
          });
        }
      }

      if (res.data.varList) {
        let list = res.data.varList;

        currentPage++;
        totalPage = res.data.totalPage || 1;
        this.setData({
          my_invite_list: this.data.my_invite_list.concat(list),
        });
      }

      if (res.data.jiHuoInfo && res.data.jiHuoInfo.totalSize) {
        this.setData({
          totalResult: res.data.jiHuoInfo.totalSize,
        });
      }
    }
  },

  toCash() {
    wx.navigateTo({
      url: "/pages/invite/cash/cash",
    });
  },
  /**
   * 获取邀请人列表
   */
  initInviteList() {
    ;
    if (loading) {
      return;
    }

    loading = true;
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    getInviteList({
      showCount: showCount,
      currentPage: currentPage,
    })
      .then((res) => {
        if (res) {
          this.handleInviteList(res);
        }
        loading = false;
        wx.hideLoading();
      })
      .catch((err) => {
        loading = false;
        wx.hideLoading();

      });
    // .finally(() => {
    //   loading = false;
    //   wx.hideLoading()
    // })
  },
  /**
   * 通过scene 获取 用户信息 自动登录 并获取邀请人信息列表
   */
  initInviteListBySCENE() {
    getTokenById({
      scene: this.data.scene,
    })
      .then((res) => {
        //  
        if (res.token) {

          wx.setStorageSync("token", res.token);
          getApp().globalData.token = res.token;
          return getUserInfo({
            token: res.token,
          });
        } else {
          return;
        }
      })
      .then((res) => {
        ;
        if (res) {
          // this.my_invite_key = res.invite_key
          user_name = res.user_name;
          wx.setStorageSync("invite_key", res.invite_key);
          wx.setStorageSync("openId", res.wx_openid);
          getApp().globalData.headerImgPath = res.headimg_url;
          this.setData({
            my_invite_key: res.invite_key,
          });
          return getInviteList({
            showCount: showCount,
            currentPage: currentPage,
          });
        }
      })
      .then((res) => {
        if (res) {
          this.requestPosterQRcode();
          this.handleInviteList(res);
        }
      })
      .catch((err) => {

      });
  },
  requestPosterQRcode: function () {
    let that = this;
    getPosterQRcode({
      page: "pages/regist/regist",
      scene: this.data.my_invite_key,
      logoPath: getApp().globalData.headerImgPath,
    }).then((res) => {
      this.setData({
        QRcodeUrl: res.smallProgramCode,
      });
    });
  },
  savePoster: function () {
    const that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: "图片已保存到相册，赶紧晒一下吧~",
          showCancel: false,
          confirmText: "好的",
          confirmColor: "#333",
          success: function (res) {
            ;

            // wx.hideLoading();
          },
          fail: function (res) { },
        });
      },
      fail(err) {
        ;
        if (
          err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" ||
          err.errMsg === "saveImageToPhotosAlbum:fail auth deny" ||
          err.errMsg === "saveImageToPhotosAlbum:fail authorize no response"
        ) {
          wx.hideLoading();
          wx.showModal({
            title: "提示",
            content: "需要您授权保存相册",
            showCancel: false,
            success: (modalSuccess) => {
              wx.openSetting({
                success(settingdata) {
                  ;
                },
                fail(failData) {
                  ;
                },
                complete(finishData) {
                  ;
                },
              });
            },
          });
        }
      },
    });
  },
  downLoadImg: function (netUrl, storageKeyUrl) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: netUrl, //请求的网络图片路径
        success: function (res) {
          //请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
          wx.setStorageSync(storageKeyUrl, res.path);
          resolve(res.path);
        },
        fail: function (err) {
          reject(err);
        },
      });
    });
  },
  createPosterImg: function () {
    ;
    let that = this;
    wx.showLoading({
      title: "生成海报中...",
      icon: "none",
    });
    this.downLoadImg(that.data.bgImage, "bgPosterUrl")
      .then(() => {
        return this.downLoadImg(that.data.QRcodeUrl, "QRcodeUrl");
      })
      .then(() => {
        let context = wx.createCanvasContext("PosterCanvas");
        let bgPath = wx.getStorageSync("bgPosterUrl"); // 图片地址
        // let bgPath = that.data.bgImage
        let QR = wx.getStorageSync("QRcodeUrl");
        // let QR = that.data.QRcodeUrl
        ;
        // 绘制图片
        context.drawImage(bgPath, 0, 0, 375, 667);
        context.beginPath();
        context.arc(189, 440, 60, 0, 2 * Math.PI); //画出圆
        context.strokeStyle = "#ffffff";
        context.stroke();
        context.clip(); //裁剪上面的圆形

        context.drawImage(QR, 129, 381, 118, 118);
        context.draw();
        context.save();
        // 将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
        setTimeout(function () {
          wx.canvasToTempFilePath({
            canvasId: "PosterCanvas",
            success: function (res) {
              const { tempFilePath } = res;
              wx.hideLoading();
              that.setData({
                imagePath: tempFilePath,
              });
              that.savePoster();
            },
            fail: function (res) {
              wx.hideLoading();
            },
          });
        }, 1000);
      })
      .catch((err) => {

      });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {

    if (options.scene) {
      this.setData({
        scene: options.scene,
      });
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // const animation = wx.createAnimation({
    //   duration: 500,
    //   delay: 0,
    //   timingFunction: "linear"
    // });
    // setInterval(() => {
    //   animation.scale(1.2).step().scale(1).step();
    //   this.setData({
    //     animationData: animation.export(),
    //   });
    // }, 500);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.setData({
      back: getCurrentPages().length > 1
    })
    if (!getApp().globalData.token) {
      // getApp().initUserInfo();
      return;
    }
    loading = false;
    if (getApp().globalData.isNotPageShow) {
      getApp().globalData.isNotPageShow = false;
      return;
    }
    user_name = getApp().globalData.user_name || "著名主持人";
    this.setData({
      my_invite_key: getinviteKey(),
      incomePercentage: getApp().globalData.income_rate + "%",
      // my_invite_list: [],
    });
    if (this.data.scene) {
      this.initInviteListBySCENE();
    } else {

    }
    if (getToken()) {
      loadingInfo({
        applied: "0",
        currentPage: 1,
        showCount: "20"
      }).then((res) => {

        this.setData({
          userlist: res.data.list,
          inviteInfo: res.data.info
        })
      })
      this.initInviteList();
      this.requestPosterQRcode();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  async onReachBottom() {
    let that = this;
    let page = ++that.data.page;
    // let userinfo = that.data.userlist
    // let data_params = {
    //   applied: "0",
    //   currentPage: page,
    //   showCount: "5",
    //   token:
    //     "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHQiOjE2MTkwMDI1MzYxMDQsInVpZCI6IjEiLCJpYXQiOjE2MTgzOTc3MzYxMDR9.NKznCiTd-HvtVLzyf4ITXcCLSqrX_Jpe1s0MgJEOss0",
    // };
    await loadingInfo({
      applied: "0",
      currentPage: page,
      showCount: "20"
    }).then((res) => {

      let carts = that.data.userlist;
      let temparr = res.data.list;
      let totalPage = res.data.totalPage
      if (totalPage <= page) {
        ;
        wx.showToast({
          title: "没有了",
          icon: "none",
        });
      } else {
        temparr = carts.concat(temparr);
        that.setData({
          userlist: temparr,
        });
      }
    })
      // wx.request({
      //   url: "https://www.hudongmiao.com/hb/getMyInviterList",
      //   data: data_params,
      //   success(res) {
      //      
      //     let carts = that.data.userlist;
      //     let temparr = res.data.data.list;
      //     if (!temparr) {
      //       wx.showToast({
      //         title: "没有了",
      //         icon: "none",
      //       });
      //     } else {
      //       temparr = carts.concat(temparr);
      //       that.setData({
      //         userlist: temparr,
      //       });
      //     }
      //   },
      // });
      ;
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    getApp().globalData.isNotPageShow = true;
    return {
      title: `${user_name || ""}邀请您加入嗨喵悦动`,
      path: "/pages/regist/regist?share_invite_key=" + this.data.my_invite_key,
      // imageUrl: 'https://ustatic.hudongmiao.com/joymew-assistant/invite/invite_wx.png'
      imageUrl: getSharePng(),
    };
  },
});
